//
//  CatTimingFeedVController.m
//  DoorBell
//
//  Created by Chun Hung Cheung on 2023/3/18.
//  Copyright © 2023 Chun Hung Cheung. All rights reserved.
//

#import "CatTimingFeedVController.h"
#import "CatFeedVController.h"
@interface CatTimingFeedVController ()<UIPickerViewDataSource,UIPickerViewDelegate>
@property(nonatomic,strong)UIPickerView *pickview;
@property(nonatomic,strong)NSMutableArray *data1Array;
@property(nonatomic,strong)NSMutableArray *data2Array;
@property(nonatomic,assign)NSInteger startTimeHourSelectedRow;
@property(nonatomic,assign)NSInteger startTimeMinSelectedRow;
@property(nonatomic,strong)UIButton *saveButton;
@property(nonatomic,strong)UIView *buttonView;
@property(nonatomic,strong)NSMutableArray *selectedweeksrAray;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UILabel *numberLabel;
@property(nonatomic,copy)NSString *weekStr;

//份数
@property(nonatomic,copy)NSString *weightStr;

//小时时间
@property(nonatomic,copy)NSString *hourTimeStr;
//分钟时间
@property(nonatomic,copy)NSString *minTimeStr;

//周期
@property(nonatomic,copy)NSString *periodStr;

//开关
@property(nonatomic,copy)NSString *statusStr;
@property (nonatomic,strong)dispatch_source_t wake_up_timer;
@property(nonatomic, assign)BOOL cancelpost;
@end

@implementation CatTimingFeedVController

- (void)viewDidLoad {
    [super viewDidLoad];
     self.view.backgroundColor = [UIColor whiteColor];
    [self setup];
     self.weekStr = @"1111111";
     self.periodStr = [self getHexByBinary:self.weekStr];
     self.selectedweeksrAray  =[NSMutableArray array];
     self.data1Array = [self addAata1Array:24];
     self.data2Array = [self addAata2Array:60];
     self.pickview.backgroundColor = [UIColor whiteColor];
    
   [self.pickview selectRow:0 inComponent:0 animated:YES];
    self.startTimeHourSelectedRow = 0;
 
   [self.pickview selectRow:0 inComponent:1 animated:YES];
    self.startTimeMinSelectedRow = 0;
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(meal_plan_result:) name:@"meal_plan" object:nil];
    
    [self.pickview reloadAllComponents];
    [self.pickview selectRow:self.startTimeHourSelectedRow inComponent:0 animated:YES];
    [self.pickview selectRow:self.startTimeMinSelectedRow inComponent:1 animated:YES];
    
     self.buttonView.backgroundColor = [UIColor whiteColor];
    [self addButton];
     self.bottomView.backgroundColor = [UIColor whiteColor];
}

- (void)meal_plan_result:(NSNotification*)cation
{
    [SVProgressHUD dismiss];
    [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Operation successful",nil)];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if(@available(iOS 15.0,*)){
      UINavigationBarAppearance *apperance=[[UINavigationBarAppearance alloc]init];
      apperance.backgroundColor = [UIColor whiteColor];
      self.navigationController.navigationBar.standardAppearance = apperance;
      self.navigationController.navigationBar.scrollEdgeAppearance = apperance;
    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"devst" object:nil];
    
}

- (void)setup
{
     UIButton *backbtn = [UIButton buttonWithType:UIButtonTypeCustom];
     backbtn.frame = CGRectMake(0,0,40,80);
     backbtn.contentHorizontalAlignment =  UIControlContentHorizontalAlignmentLeft;
    [backbtn setImage:[UIImage imageNamed:@"cat_alarm_back"] forState:UIControlStateNormal];
    [backbtn addTarget:self action:@selector(selectLeftActionClick) forControlEvents:UIControlEventTouchUpInside];
    [backbtn SG_imagePositionStyle:SGImagePositionStyleDefault spacing:5];
     self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backbtn];
 
    UILabel *titleLabel  = [[UILabel alloc]init];
    titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
    titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:20.0];
    titleLabel.text = NSLocalizedString(@"添加定时",nil);
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.frame = CGRectMake(0, 0, 80, 25);
     self.navigationItem.titleView = titleLabel;
    
    _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _saveButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
   [_saveButton addTarget:self action:@selector(saveButtonClick:) forControlEvents:UIControlEventTouchUpInside];
   [_saveButton setTitleColor:[UIColor orangeColor] forState:UIControlStateNormal];
    _saveButton.userInteractionEnabled = YES;
   
   [_saveButton setTitle:NSLocalizedString(@"保存", nil) forState:UIControlStateNormal];
    _saveButton.frame = CGRectMake(0,0,32+19,20);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:_saveButton];
}

- (void)saveButtonClick:(UIButton*)sender
{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(devstClick:) name:@"devst" object:nil];
    
    FBDevicesList *list = [[FBDevicesList bg_find:@"FBDevicesList" where:[NSString stringWithFormat:@"where %@=%@ and %@=%@",bg_sqlKey(@"userName"),bg_sqlValue([Tooles getuserToken]), bg_sqlKey(@"bid"),bg_sqlValue(self.bid)]] firstObject];
    if (list.status == 2) {
        
        if(!self.periodStr) {
            [SVProgressHUD showErrorWithStatus: NSLocalizedString(@"Please set the cycle",nil)];
            return;
        }
        [SVProgressHUD showWithStatus:NSLocalizedString(@"设置中，请稍候",nil)];
        // 发送唤醒指令 收到结果后设置为空 如果为yes 则发送唤醒指令
        __block int timeout = 30*200*5; // 倒计时时间
        _cancelpost = NO;
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        _wake_up_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_wake_up_timer,dispatch_walltime(NULL, 0),200.0*NSEC_PER_MSEC, 0); //每秒执行
        dispatch_source_set_event_handler(_wake_up_timer, ^{
            if(_cancelpost){ // 倒计时结束，关闭
                dispatch_source_cancel(_wake_up_timer);
                _wake_up_timer = nil;
                [self post_data];
            }else{
                NSString *Str =   [NSString stringWithFormat:@"{\"method\":\"wake_up_t1_r700\",\"from\":\"%@\",\"to\":\"%@\",\"id\":100006071,\"value\": {\"id\":2,\"val\":1}}",[[NSUserDefaults standardUserDefaults] objectForKey:@"EquesUid"],self.bid];
                [YKBusinessFramework equesSendData:Str];
                 timeout-=200;
                if (timeout <= 0) {
                    dispatch_source_cancel(_wake_up_timer);
                    _wake_up_timer = nil;
                }
            }
        });
         dispatch_resume(_wake_up_timer);
    }else if (list.status == 1){
        
        
        [SVProgressHUD showWithStatus:NSLocalizedString(@"设置中，请稍候",nil)];
        
        [self post_data];
        
    }
}

- (void)post_data
{
    if(self.periodStr){
        
        if(!self.hourTimeStr){
            
            NSString *str = [self ToHex:self.startTimeHourSelectedRow];
            
            if(str.length == 1){
                self.hourTimeStr = [NSString stringWithFormat:@"0%@",str];
            }else{
                self.hourTimeStr = str;
            }
        }
        
        if(!self.minTimeStr){

            int result;
            NSString *st = [self.data2Array firstObject];
            result = [[st substringToIndex:2] intValue];
            NSLog(@"去掉前导零后的整数：%d", result);
            
            NSString *str = [self ToHex:result];
            
            if(str.length == 1){
                self.minTimeStr = [NSString stringWithFormat:@"0%@",str];
            }else{
                self.minTimeStr = str;
            }
        }
        
        if(!self.weightStr){
            
            NSString *str = [self ToHex:1];
            
            if(str.length == 1){
                self.weightStr = [NSString stringWithFormat:@"0%@",str];
            }else{
                self.weightStr = str;
            }
        }
        
        NSString *str = [NSString stringWithFormat:@"%@%@%@%@01",self.periodStr,self.hourTimeStr,self.minTimeStr,self.weightStr];
        
        if ([self.plan containsObject:[str lowercaseString]]) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The feeding plan already exists,please do not add it again!",nil) duration:2];
            return;
        }
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *str in self.plan) {
             NSString *sub_str = [str substringToIndex:6];
             NSLog(@"sub_str --%@",sub_str);
            [array addObject:sub_str];
        }
        
       NSLog(@"array --%@",array);
       NSString *cur_str = [str lowercaseString];
       NSString *sub_str = [cur_str substringToIndex:6];
        
        if ([array containsObject:sub_str]) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"The feeding plan already exists,please do not add it again!",nil) duration:2];
            return;
        }
        
        
        NSMutableArray *arr_plan = [NSMutableArray array];
        if (self.plan.count > 0) {
            for (NSString *plan in self.plan) {
                [arr_plan addObject:plan];
            }
            [arr_plan addObject:str];
        }else{
            [arr_plan addObject:str];
        }
        
        NSArray *valueArray = @[@"control",self.bid,arr_plan];
        NSArray *keyArray = @[@"method",@"to",@"meal_plan"];
        NSDictionary *alternativeDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
        
        NSError *error;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:alternativeDic options:NSJSONWritingPrettyPrinted error:&error];
        NSString *pCfgBufString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        NSLog(@"pCfgBufString-->%@",pCfgBufString);
        [YKBusinessFramework equesSendData:pCfgBufString];
    }else{
        [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"Please set the cycle",nil)];
    }
}


- (void)devstClick:(NSNotification*)notification
{
    /*
     {
         bid = 1fd834a600472ebe24cb01e03f9416d1;
         method = devst;
         name = "e0d31a150c6f-1fd834a6";
         remoteupg = 2;
         role = 27;
         status = 0;
         stat = 0;
         type = 27;
         uid = 1fd834a600472ebe24cb01e03f9416d1;
     }
    */
    
    NSDictionary *dict = (NSDictionary*)notification.object;
    NSString *bid = [dict objectForKey:@"bid"];
    if (![bid isEqualToString:self.bid]) {
         return;
    }

    if ([self.bid isEqualToString:bid] && [[dict objectForKey:@"stat"] intValue] == 1) {
         self.cancelpost = YES;
    }else{
        self.cancelpost = NO;
    }
}




- (void)selectLeftActionClick
{
    if (_wake_up_timer) {
        dispatch_source_cancel(_wake_up_timer);
        _wake_up_timer = nil;
    }
    [self.navigationController popViewControllerAnimated:YES];
}


- (NSMutableArray*)addAata1Array:(int)number
{
    [_data1Array removeAllObjects];
     _data1Array = nil;
     _data1Array = [NSMutableArray array];
    for (int i = 0; i < number; i++) {
        [_data1Array addObject:[NSString stringWithFormat:@"%02d时",i]];
    }
    return _data1Array;
}

- (NSMutableArray*)addAata2Array:(int)number
{
    [_data2Array removeAllObjects];
     _data2Array = nil;
     _data2Array = [NSMutableArray array];
    
    int index = number / 5 ;
    int j = 0;
    for (int i = 0; i < index; i++) {
        if (i == 11) {
            j = 55;
        }else if (i == 0){
            j = 0;
        }else{
            j += 5;
        }
       [_data2Array addObject:[NSString stringWithFormat:@"%02d分",j]];
    }
    return _data2Array;
}


- (UIPickerView*)pickview
{
    if (!_pickview) {
        // 设置UIPickerView
         _pickview = [[UIPickerView alloc]init];
         _pickview.backgroundColor = [UIColor whiteColor];
         _pickview.dataSource = self;
         _pickview.delegate = self;
        [self.view addSubview:_pickview];
        [_pickview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.mas_equalTo(216);
            make.top.equalTo(self.view.mas_top).offset(25);
        }];
    }
    return _pickview;
}

#pragma mark - UIPickerViewDataSource 组数
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return self.data1Array.count;
    }else{
        return self.data2Array.count;
    }
}
#pragma mark - UIPickerViewDelegate

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 40;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return self.data1Array[row];
    }else{
        return self.data2Array[row];
    }
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    switch (component) {
      case 0:
        {
            NSLog(@"开始时间第一列-->%@",self.data1Array[row]);
            self.startTimeHourSelectedRow = row;
            NSString *str = [self ToHex:self.startTimeHourSelectedRow];
            
            if(str.length == 1){
                self.hourTimeStr = [NSString stringWithFormat:@"0%@",str];
            }else{
                self.hourTimeStr = str;
            }
            
            NSLog(@"10进制转16进制str-->%@",self.hourTimeStr);
        }
          break;
      case 1:
        {
            NSLog(@"开始时间第二列-->%@",self.data2Array[row]);
            
            NSString *st = self.data2Array[row];
            int result = [[st substringToIndex:2] intValue];
            NSLog(@"去掉前导零后的整数：%d", result);
            
            self.startTimeMinSelectedRow = result;
            NSString *str = [self ToHex:self.startTimeMinSelectedRow];
            
            if(str.length == 1){
                self.minTimeStr = [NSString stringWithFormat:@"0%@",str];
            }else{
                self.minTimeStr = str;
            }
            
            NSLog(@"10进制转16进制str-->%@",self.minTimeStr);
        }
          break;
            
      default:
            break;
    }
     [self.pickview reloadAllComponents];
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    [self changeSpearatorLineColor];
    NSString *title = [self pickerView:pickerView titleForRow:row forComponent:component];
    UILabel* pickerLabel = (UILabel*)view;
    if(!pickerLabel){
         pickerLabel = [[UILabel alloc]init];
        [pickerLabel sizeToFit];
         pickerLabel.textAlignment = NSTextAlignmentCenter;
         pickerLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:18];
         pickerLabel.textColor = [HexChangeRGB colorWithHexString:@"#000000"];
    }
    //调用委托方法，获取需要显示的数据。
     pickerLabel.text = title;
    return pickerLabel;
}

//取到选中行背景的图层,修改颜色
#pragma mark - 改变分割线的颜色 和 选中的背景色
- (void)changeSpearatorLineColor {
    
    for(UIView *speartorView in self.pickview.subviews) {
 
        if (speartorView.frame.size.height < 80) {//找出当前的 View
            /// 背景
            // 添加分割线 (判断只添加一次  滑动不断刷新)
            if (speartorView.subviews.count ==0){
                UIView *line = [self lineView];
                line.frame = CGRectMake(0, 0, kScreenWidth, 0.5);
                [speartorView addSubview:line];
                
                UIView *line2 = [self lineView];
                line2.frame = CGRectMake(0, speartorView.frame.size.height-1, kScreenWidth, 0.5);
                [speartorView addSubview:line2];
            }
 
            speartorView.backgroundColor = [UIColor clearColor];
        }else{
            speartorView.backgroundColor = [UIColor clearColor];
        }
    }
}
/// 分割线
- (UIView *)lineView {
    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 0.5)];
    line.backgroundColor = [HexChangeRGB colorWithHexString:@"#CACACA"];
    return line;
}


- (UIView*)buttonView
{
    if(!_buttonView){
        _buttonView = [[UIView alloc]init];
        [self.view addSubview:_buttonView];
        [_buttonView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.mas_equalTo(110);
            make.top.equalTo(self.pickview.mas_bottom);
        }];
        
         UIView *line = [[UIView alloc]initWithFrame:CGRectZero];
         line.backgroundColor = [HexChangeRGB colorWithHexString:@"#CACACA"];
        [_buttonView addSubview:line];
        [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_buttonView.mas_left);
            make.right.equalTo(_buttonView.mas_right);
            make.height.mas_equalTo(0.5);
            make.top.equalTo(_buttonView.mas_top);
        }];
        
         UILabel  *_titleLabel = [[UILabel alloc]init];
         _titleLabel.text = NSLocalizedString(@"重复周期",nil);
         _titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
         _titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
         _titleLabel.numberOfLines = 0;
         _titleLabel.textAlignment = NSTextAlignmentLeft;
        [_buttonView addSubview:_titleLabel];
        [_titleLabel sizeToFit];
        [_titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_buttonView.mas_left).offset(14);
            make.top.equalTo(_buttonView.mas_top).offset(20);
        }];
        
        
    }
    return _buttonView;
}

- (void)addButton
{
    for (int i = 0 ; i < 7; i ++) {
      CGFloat margin =  (kScreenWidth - 44 - 40 *7)/6;
      UIButton *_servicesButton = [[UIButton alloc]init];
       _servicesButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14];
      [_servicesButton setTitleColor:[HexChangeRGB colorWithHexString:@"#666666"] forState:UIControlStateNormal];
     [_servicesButton setTitleColor:[HexChangeRGB colorWithHexString:@"#FFFFFF"] forState:UIControlStateSelected];
     [_servicesButton addTarget:self action:@selector(servicesButtonClick:) forControlEvents:UIControlEventTouchUpInside];
     [_servicesButton setBackgroundImage:[self imageWithColor:[HexChangeRGB colorWithHexString:@"#EBEBEB"]] forState:UIControlStateNormal];
     [_servicesButton setBackgroundImage:[self imageWithColor:[HexChangeRGB colorWithHexString:@"#FF7316"]] forState:UIControlStateSelected];
      _servicesButton.layer.cornerRadius = 20;
      _servicesButton.layer.masksToBounds = YES;
      _servicesButton.tag = 1314 + i;

        switch (i) {
                case 0:
                [_servicesButton setTitle:@"周一" forState:UIControlStateNormal];
                break;
               case 1:
                [_servicesButton setTitle:@"周二" forState:UIControlStateNormal];
                break;
               case 2:
                [_servicesButton setTitle:@"周三" forState:UIControlStateNormal];
                break;
               case 3:
                [_servicesButton setTitle:@"周四" forState:UIControlStateNormal];
                break;
               case 4:
                [_servicesButton setTitle:@"周五" forState:UIControlStateNormal];
                break;
               case 5:
                [_servicesButton setTitle:@"周六" forState:UIControlStateNormal];
                break;
               case 6:
                [_servicesButton setTitle:@"周日" forState:UIControlStateNormal];
                break;
               default:
                break;
           }
        
        
      [self.selectedweeksrAray addObject:_servicesButton.titleLabel.text];
      [self.buttonView addSubview:_servicesButton];
      [_servicesButton mas_makeConstraints:^(MASConstraintMaker *make) {
         make.left.equalTo(self.buttonView.mas_left).offset(22 + (margin+40)*i);
         make.width.height.mas_equalTo(40);
         make.bottom.equalTo(self.buttonView.mas_bottom).offset(-10);
      }];
      
        for (NSString *weeks in self.selectedweeksrAray) {
            if ([_servicesButton.titleLabel.text isEqualToString:weeks]) {
                 _servicesButton.selected = YES;
            }
        }
    }
}


- (UIImage *)imageWithColor:(UIColor *)color{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
    return image;
}


- (void)servicesButtonClick:(UIButton*)sender
{
    if (sender.selected) {
        if (self.selectedweeksrAray.count == 1) {
            [SVProgressHUD showErrorWithStatus:NSLocalizedString(@"至少选择一个周期!",nil)];
            return;
        }
    }
    sender.selected = !sender.selected;
   
    if (![self.selectedweeksrAray containsObject:sender.titleLabel.text]) {
         [self.selectedweeksrAray addObject:sender.titleLabel.text];
        
          NSInteger index = sender.tag - 1314;
          self.weekStr = [self.weekStr stringByReplacingCharactersInRange:NSMakeRange(index,1) withString:@"1"];
        
    }else{
         [self.selectedweeksrAray removeObject:sender.titleLabel.text];
          NSInteger index = sender.tag - 1314;
          self.weekStr =  [self.weekStr stringByReplacingCharactersInRange:NSMakeRange(index,1) withString:@"0"];
    }
   
    NSLog(@"self.weekStr---%@ ---%@",self.weekStr,[self getHexByBinary:self.weekStr]);
    self.periodStr = [self getHexByBinary:self.weekStr];
}



- (UIView*)bottomView
{
     if(!_bottomView){
         _bottomView = [[UIView alloc]init];
         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapClick)];
        [_bottomView addGestureRecognizer:tap];
        [self.view addSubview:_bottomView];
        [_bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.view.mas_left);
            make.right.equalTo(self.view.mas_right);
            make.height.mas_equalTo(50);
            make.top.equalTo(self.buttonView.mas_bottom).offset(14);
        }];
        
         UILabel  *_titleLabel = [[UILabel alloc]init];
         _titleLabel.text = NSLocalizedString(@"份数",nil);
         _titleLabel.textColor = [HexChangeRGB colorWithHexString:@"#333333"];
         _titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16.0];
         _titleLabel.numberOfLines = 0;
         _titleLabel.textAlignment = NSTextAlignmentLeft;
        [_bottomView addSubview:_titleLabel];
        [_titleLabel sizeToFit];
        [_titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(_bottomView.mas_left).offset(14);
            make.centerY.equalTo(_bottomView.mas_centerY);
        }];
        
         UIImageView *_arrowicon = [[UIImageView alloc]init];
        [_bottomView addSubview:_arrowicon];
        [_arrowicon mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(7);
            make.height.mas_equalTo(12);
            make.centerY.equalTo(_bottomView.mas_centerY);
            make.right.equalTo(_bottomView.mas_right).offset(-14);
        }];
        _arrowicon.image = [UIImage imageNamed:@"voice_v2_arrow_next"];
        
        _numberLabel = [[UILabel alloc]init];
        _numberLabel.text = @"1";
        _numberLabel.textColor = [HexChangeRGB colorWithHexString:@"#666666"];
        _numberLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:14.0];
        _numberLabel.numberOfLines = 0;
        _numberLabel.textAlignment = NSTextAlignmentLeft;
       [_bottomView addSubview:_numberLabel];
       [_numberLabel sizeToFit];
       [_numberLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
           make.right.equalTo(_bottomView.mas_right).offset(-30);
           make.centerY.equalTo(_bottomView.mas_centerY);
       }];
    }
    return _bottomView;
}

- (void)tapClick
{
    NSLog(@"设置份数");
    CatFeedVController *feedvc = [[CatFeedVController alloc] initWithType:kWHCustomAnimationTypePush];
    feedvc.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.4];
    feedvc.definesPresentationContext = YES;
    feedvc.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    feedvc.weightblock = ^(NSInteger weight) {
         self.numberLabel.text = [NSString stringWithFormat:@"%ld",weight];
         NSString *weightstr = [self ToHex:weight];
        if(weightstr.length == 1){
            self.weightStr = [NSString stringWithFormat:@"0%@",weightstr];
        }else{
            self.weightStr = weightstr;
        }
         NSLog(@"显示份数--%@",self.weightStr);
    };
   [self presentViewController:feedvc animated:YES completion:nil];
}


//10进制转16进制
-(NSString *)ToHex:(long long int)tmpid
{
    NSString *nLetterValue;
    NSString *str = @"";
    long long int ttmpig;
    for (int i = 0; i<9; i++) {
       ttmpig = tmpid % 16;
       tmpid = tmpid / 16;
        switch (ttmpig)
        {
            case 10:
                nLetterValue = @"A";break;
            case 11:
                nLetterValue = @"B";break;
            case 12:
                nLetterValue = @"C";break;
            case 13:
                nLetterValue = @"D";break;
            case 14:
                nLetterValue = @"E";break;
            case 15:
                nLetterValue = @"F";break;
            default:
                nLetterValue = [[NSString alloc]initWithFormat:@"%lli",ttmpig];
                  
        }
        str = [nLetterValue stringByAppendingString:str];
        
        if (tmpid == 0) {
            break;
        }
  
    }
    return str;
}

/**
 二进制转换成十六进制
 @param binary 二进制数
 @return 十六进制数
 */
- (NSString *)getHexByBinary:(NSString *)binary {
    NSMutableDictionary *binaryDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [binaryDic setObject:@"0" forKey:@"0000"];
    [binaryDic setObject:@"1" forKey:@"0001"];
    [binaryDic setObject:@"2" forKey:@"0010"];
    [binaryDic setObject:@"3" forKey:@"0011"];
    [binaryDic setObject:@"4" forKey:@"0100"];
    [binaryDic setObject:@"5" forKey:@"0101"];
    [binaryDic setObject:@"6" forKey:@"0110"];
    [binaryDic setObject:@"7" forKey:@"0111"];
    [binaryDic setObject:@"8" forKey:@"1000"];
    [binaryDic setObject:@"9" forKey:@"1001"];
    [binaryDic setObject:@"A" forKey:@"1010"];
    [binaryDic setObject:@"B" forKey:@"1011"];
    [binaryDic setObject:@"C" forKey:@"1100"];
    [binaryDic setObject:@"D" forKey:@"1101"];
    [binaryDic setObject:@"E" forKey:@"1110"];
    [binaryDic setObject:@"F" forKey:@"1111"];
    
    if (binary.length % 4 != 0) {
        
        NSMutableString *mStr = [[NSMutableString alloc]init];;
        for (int i = 0; i < 4 - binary.length % 4; i++) {
            
            [mStr appendString:@"0"];
        }
        binary = [mStr stringByAppendingString:binary];
    }
    NSString *hex = @"";
    for (int i=0; i<binary.length; i+=4) {
        
        NSString *key = [binary substringWithRange:NSMakeRange(i, 4)];
        NSString *value = [binaryDic objectForKey:key];
        if (value) {
            
            hex = [hex stringByAppendingString:value];
        }
    }
    return hex;
}


/**
 十六进制转换为二进制
 
 @param hex 十六进制数
 @return 二进制数
 */
- (NSString *)getBinaryByHex:(NSString *)hex {
    
    NSMutableDictionary *hexDic = [[NSMutableDictionary alloc] initWithCapacity:16];
    [hexDic setObject:@"0000" forKey:@"0"];
    [hexDic setObject:@"0001" forKey:@"1"];
    [hexDic setObject:@"0010" forKey:@"2"];
    [hexDic setObject:@"0011" forKey:@"3"];
    [hexDic setObject:@"0100" forKey:@"4"];
    [hexDic setObject:@"0101" forKey:@"5"];
    [hexDic setObject:@"0110" forKey:@"6"];
    [hexDic setObject:@"0111" forKey:@"7"];
    [hexDic setObject:@"1000" forKey:@"8"];
    [hexDic setObject:@"1001" forKey:@"9"];
    [hexDic setObject:@"1010" forKey:@"A"];
    [hexDic setObject:@"1011" forKey:@"B"];
    [hexDic setObject:@"1100" forKey:@"C"];
    [hexDic setObject:@"1101" forKey:@"D"];
    [hexDic setObject:@"1110" forKey:@"E"];
    [hexDic setObject:@"1111" forKey:@"F"];
    
    NSString *binary = @"";
    for (int i=0; i<[hex length]; i++) {
        
        NSString *key = [hex substringWithRange:NSMakeRange(i, 1)];
        NSString *value = [hexDic objectForKey:key.uppercaseString];
        if (value) {
            binary = [binary stringByAppendingString:value];
        }
    }
    return binary;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"meal_plan" object:nil];
}

@end
